import React, {useCallback, useEffect, useRef, useState, useMemo} from 'react'
import {Alert, FlatList, RefreshControl, TouchableOpacity, View,} from 'react-native'
import {SafeAreaView, useSafeAreaInsets} from 'react-native-safe-area-context'
import {Avatar, Badge, Button, Card, Icon, Text} from '@rneui/themed'
import {LeaveStatus, PageParams, RegisterApi, RegisterVO} from '../../api/leave'
import { ProcessInstanceApi } from '../../api/process'
import {formatDate} from '../../utils/dateFormatter'
import ApprovalButtons from './components/ApprovalButtons'

const LeaveItem = React.memo(({ 
	item, 
	onViewDetail, 
	onEdit, 
	onCancel, 
	getStatusLabel, 
	getStatusColor 
}: {
	item: RegisterVO
	onViewDetail: (item: RegisterVO) => void
	onEdit: (item: RegisterVO) => void
	onCancel: (item: RegisterVO) => void
	getStatusLabel: (status: LeaveStatus) => string
	getStatusColor: (status: LeaveStatus) => string
}) => {
	const timeString = useMemo(() => {
		if (item.createTime) {
			const date = new Date(item.createTime)
			return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
		}
		return '00:00'
	}, [item.createTime])

	const leaveDays = useMemo(() => {
		if (item.startDate && item.endDate) {
			return Math.ceil((new Date(item.endDate).getTime() - new Date(item.startDate).getTime()) / (1000 * 60 * 60 * 24)) + 1
		}
		return 1
	}, [item.startDate, item.endDate])

	const formattedStartDate = useMemo(() => formatDate(item.startDate), [item.startDate])
	const formattedEndDate = useMemo(() => formatDate(item.endDate), [item.endDate])

	return (
		<TouchableOpacity onPress={() => onViewDetail(item)}>
			<Card containerStyle={styles.cardContainer}>
				<View style={styles.cardHeader}>
					<View style={styles.leftSection}>
						<Avatar
							size={30}
							title={item.nickName?.charAt(0) || '未'}
							containerStyle={styles.avatar}
							titleStyle={styles.avatarText}
						/>
						<View style={styles.headerInfo}>
							<Text style={styles.titleText}>
								{item.nickName || '未知'}提交的请假
							</Text>
						</View>
					</View>
					<Text style={styles.timeText}>{timeString}</Text>
				</View>

				<View style={styles.cardContent}>
					<View style={styles.contentRow}>
						<Text style={styles.contentLabel}>请假类型：</Text>
						<Text style={styles.contentValue}>{item.reasons || '事假'}</Text>
					</View>
					<View style={styles.contentRow}>
						<Text style={styles.contentLabel}>开始时间：</Text>
						<Text style={styles.contentValue}>{formattedStartDate}</Text>
					</View>
					<View style={styles.contentRow}>
						<Text style={styles.contentLabel}>结束时间：</Text>
						<Text style={styles.contentValue}>{formattedEndDate}</Text>
					</View>
					<View style={styles.contentRow}>
						<Text style={styles.contentLabel}>总计天数：</Text>
						<Text style={styles.contentValue}>{leaveDays}</Text>
					</View>
				</View>

				<View style={styles.cardFooter}>
					<View style={styles.buttonRow}>
						<Badge
							value={getStatusLabel(item.status ?? LeaveStatus.PENDING)}
							badgeStyle={[styles.statusBadge, { backgroundColor: getStatusColor(item.status ?? LeaveStatus.PENDING) }]}
							textStyle={styles.statusBadgeText}
						/>
						<View style={styles.actionSection}>
							{(item.status === LeaveStatus.PENDING || item.status === LeaveStatus.APPROVING) && (
								<Button
									title="编辑"
									size="sm"
									type="outline"
									buttonStyle={styles.actionButton}
									titleStyle={styles.actionButtonText}
									onPress={() => onEdit(item)}
								/>
							)}
							{item.processInstanceId && 
								item.status !== LeaveStatus.COMPLETED && 
								item.status !== LeaveStatus.REJECTED && 
								item.status !== LeaveStatus.CANCELLED && (
								<Button
									title="撤销"
									size="sm"
									type="outline"
									buttonStyle={styles.cancelActionButton}
									titleStyle={styles.cancelActionText}
									onPress={() => onCancel(item)}
								/>
							)}
						</View>
					</View>
				</View>
			</Card>
		</TouchableOpacity>
	)
})

const TodoItem = React.memo(({ 
	item, 
	onViewDetail, 
	onRefresh 
}: {
	item: any
	onViewDetail: (item: any) => void
	onRefresh: () => void
}) => {
	// 缓存计算结果
	const timeString = useMemo(() => {
		if (item.createTime) {
			const date = new Date(item.createTime)
			return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
		}
		return '00:00'
	}, [item.createTime])

	const userInfo = useMemo(() => {
		if (item.leaveDetail?.nickName) {
			return item.leaveDetail.nickName
		}
		const startUser = item.processInstance?.startUser
		if (startUser?.nickname) {
			return startUser.nickname
		}
		return startUser?.name || startUser?.realName || '未知用户'
	}, [item.leaveDetail, item.processInstance])

	const reasons = useMemo(() => {
		if (item.reasonsType) {
			return item.reasonsType
		}
		if (item.leaveDetail?.reasons) {
			return item.leaveDetail.reasons
		}
		return item.reasons || '未知'
	}, [item.reasonsType, item.leaveDetail, item.reasons])

	const formattedStartDate = useMemo(() => {
		if (item.time) {
			const timeParts = item.time.split('至')
			return timeParts[0] || ''
		}
		if (item.leaveDetail?.startDate) {
			return formatDate(item.leaveDetail.startDate)
		}
		return ''
	}, [item.time, item.leaveDetail])

	const formattedEndDate = useMemo(() => {
		if (item.time) {
			const timeParts = item.time.split('至')
			return timeParts[1] || ''
		}
		if (item.leaveDetail?.endDate) {
			return formatDate(item.leaveDetail.endDate)
		}
		return ''
	}, [item.time, item.leaveDetail])

	const leaveDays = useMemo(() => {
		if (item.time) {
			const timeParts = item.time.split('至')
			if (timeParts.length === 2) {
				const startDateStr = timeParts[0].trim()
				const endDateStr = timeParts[1].trim()
				
				// 尝试解析日期格式 "2025-8-14"
				const parseDate = (dateStr: string) => {
					const parts = dateStr.split('-')
					if (parts.length === 3) {
						const year = parseInt(parts[0], 10)
						const month = parseInt(parts[1], 10) - 1 
						const day = parseInt(parts[2], 10)
						return new Date(year, month, day)
					}
					return null
				}
				
				const startDate = parseDate(startDateStr)
				const endDate = parseDate(endDateStr)
				
				if (startDate && endDate) {
					return Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24)) + 1
				}
			}
		}
		
		if (item.leaveDetail?.startDate && item.leaveDetail?.endDate) {
			return Math.ceil((new Date(item.leaveDetail.endDate).getTime() - new Date(item.leaveDetail.startDate).getTime()) / (1000 * 60 * 60 * 24)) + 1
		}
		return 1
	}, [item.time, item.leaveDetail])

	return (
		<TouchableOpacity onPress={() => onViewDetail(item)}>
			<Card containerStyle={styles.cardContainer}>
				<View style={styles.cardHeader}>
					<View style={styles.leftSection}>
						<Avatar
							size={30}
							title={userInfo.charAt(0) || '未'}
							containerStyle={styles.avatar}
							titleStyle={styles.avatarText}
						/>
						<View style={styles.headerInfo}>
							<Text style={styles.titleText}>
								{userInfo}提交的请假
							</Text>
							{/* <Text style={styles.subtitleText}>
								{deptInfo}
							</Text> */}
						</View>
					</View>
					<Text style={styles.timeText}>{timeString}</Text>
				</View>

				<View style={styles.cardContent}>
					<View style={styles.contentRow}>
						<Text style={styles.contentLabel}>请假类型：</Text>
						<Text style={styles.contentValue}>{reasons}</Text>
					</View>
					<View style={styles.contentRow}>
						<Text style={styles.contentLabel}>开始时间：</Text>
						<Text style={styles.contentValue}>{formattedStartDate}</Text>
					</View>
					<View style={styles.contentRow}>
						<Text style={styles.contentLabel}>结束时间：</Text>
						<Text style={styles.contentValue}>{formattedEndDate}</Text>
					</View>
					<View style={styles.contentRow}>
						<Text style={styles.contentLabel}>总计天数：</Text>
						<Text style={styles.contentValue}>{leaveDays}</Text>
					</View>
					<View style={styles.contentRow}>
						<Text style={styles.contentLabel}>当前任务：</Text>
						<Text style={styles.contentValue}>{item.name || '待审批'}</Text>
					</View>
				</View>

				<View style={styles.cardFooter}>
					<View style={styles.buttonRow}>
						<ApprovalButtons
							taskId={item.id}
							onApprovalComplete={onRefresh}
							showFullWidth={true}
						/>
					</View>
				</View>
			</Card>
		</TouchableOpacity>
	)
})

const DoneItem = React.memo(({ 
	item, 
	onViewDetail, 
	_onRefresh 
}: {
	item: any
	onViewDetail: (item: any) => void
	_onRefresh: () => void
}) => {
	// 缓存计算结果
	const timeString = useMemo(() => {
		if (item.createTime) {
			const date = new Date(item.createTime)
			return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
		}
		return '00:00'
	}, [item.createTime])

	const userInfo = useMemo(() => {
		if (item.leaveDetail?.nickName) {
			return item.leaveDetail.nickName
		}
		const startUser = item.processInstance?.startUser
		if (startUser?.nickname) {
			return startUser.nickname
		}
		return startUser?.name || startUser?.realName || '未知用户'
	}, [item.leaveDetail, item.processInstance])

	const reasons = useMemo(() => {
		if (item.reasonsType) {
			return item.reasonsType
		}
		if (item.leaveDetail?.reasons) {
			return item.leaveDetail.reasons
		}
		return item.reasons || '未知'
	}, [item.reasonsType, item.leaveDetail, item.reasons])

	const formattedStartDate = useMemo(() => {
		if (item.time) {
			const timeParts = item.time.split('至')
			return timeParts[0] || ''
		}
		if (item.leaveDetail?.startDate) {
			return formatDate(item.leaveDetail.startDate)
		}
		return ''
	}, [item.time, item.leaveDetail])

	const formattedEndDate = useMemo(() => {
		if (item.time) {
			const timeParts = item.time.split('至')
			return timeParts[1] || ''
		}
		if (item.leaveDetail?.endDate) {
			return formatDate(item.leaveDetail.endDate)
		}
		return ''
	}, [item.time, item.leaveDetail])

	const leaveDays = useMemo(() => {
		if (item.time) {
			const timeParts = item.time.split('至')
			if (timeParts.length === 2) {
				const startDateStr = timeParts[0].trim()
				const endDateStr = timeParts[1].trim()
				
				// 尝试解析日期格式 "2025-8-14"
				const parseDate = (dateStr: string) => {
					const parts = dateStr.split('-')
					if (parts.length === 3) {
						const year = parseInt(parts[0], 10)
						const month = parseInt(parts[1], 10) - 1 
						const day = parseInt(parts[2], 10)
						return new Date(year, month, day)
					}
					return null
				}
				
				const startDate = parseDate(startDateStr)
				const endDate = parseDate(endDateStr)
				
				if (startDate && endDate) {
					return Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24)) + 1
				}
			}
		}
		
		if (item.leaveDetail?.startDate && item.leaveDetail?.endDate) {
			return Math.ceil((new Date(item.leaveDetail.endDate).getTime() - new Date(item.leaveDetail.startDate).getTime()) / (1000 * 60 * 60 * 24)) + 1
		}
		return 1
	}, [item.time, item.leaveDetail])

	return (
		<TouchableOpacity onPress={() => onViewDetail(item)}>
			<Card containerStyle={styles.cardContainer}>
				<View style={styles.cardHeader}>
					<View style={styles.leftSection}>
						<Avatar
							size={30}
							title={userInfo.charAt(0) || '未'}
							containerStyle={styles.avatar}
							titleStyle={styles.avatarText}
						/>
						<View style={styles.headerInfo}>
							<Text style={styles.titleText}>
								{userInfo}提交的请假
							</Text>
						</View>
					</View>
					<Text style={styles.timeText}>{timeString}</Text>
				</View>

				<View style={styles.cardContent}>
					<View style={styles.contentRow}>
						<Text style={styles.contentLabel}>请假类型：</Text>
						<Text style={styles.contentValue}>{reasons}</Text>
					</View>
					<View style={styles.contentRow}>
						<Text style={styles.contentLabel}>开始时间：</Text>
						<Text style={styles.contentValue}>{formattedStartDate}</Text>
					</View>
					<View style={styles.contentRow}>
						<Text style={styles.contentLabel}>结束时间：</Text>
						<Text style={styles.contentValue}>{formattedEndDate}</Text>
					</View>
					<View style={styles.contentRow}>
						<Text style={styles.contentLabel}>总计天数：</Text>
						<Text style={styles.contentValue}>{leaveDays}</Text>
					</View>
				</View>

				{/* <View style={styles.cardFooter}>
					<View style={styles.buttonRow}>
						<Badge
							value={item.status}
							badgeStyle={[styles.statusBadge, styles.approvedBadge]}
							textStyle={styles.statusBadgeText}
						/>
					</View>
				</View> */}
			</Card>
		</TouchableOpacity>
	)
})

export const Leave = ({navigation}: any) => {
	const insets = useSafeAreaInsets()
	
	// Tab 状态管理
	const [activeTab, setActiveTab] = useState<'my' | 'todo' | 'done'>('my')
	
	const flatListRef = useRef<FlatList>(null)
	
	// 我的请假列表状态
	const [leaveList, setLeaveList] = useState<RegisterVO[]>([])
	const [loading, setLoading] = useState(false)
	const [refreshing, setRefreshing] = useState(false)
	const [total, setTotal] = useState(0)
	const [pageNo, setPageNo] = useState(1)
	const [pageSize] = useState(10)
	const pageNoRef = useRef(pageNo)

	// 待批请假列表状态
	const [todoList, setTodoList] = useState<any[]>([])
	const [todoLoading, setTodoLoading] = useState(false)
	const [todoRefreshing, setTodoRefreshing] = useState(false)
	const [todoTotal, setTodoTotal] = useState(0)
	const [todoPageNo, setTodoPageNo] = useState(1)
	const todoPageNoRef = useRef(todoPageNo)
	const [todoEnriching, setTodoEnriching] = useState(false) // 是否正在获取详细信息的加载状态

	// 已批请假列表状态
	const [doneList, setDoneList] = useState<any[]>([])
	const [doneLoading, setDoneLoading] = useState(false)
	const [doneRefreshing, setDoneRefreshing] = useState(false)
	const [doneTotal, setDoneTotal] = useState(0)
	const [donePageNo, setDonePageNo] = useState(1)
	const donePageNoRef = useRef(donePageNo)
	const [doneEnriching, setDoneEnriching] = useState(false) // 是否正在获取详细信息的加载状态

	const leaveListRef = useRef(leaveList)
	const todoListRef = useRef(todoList)
	const doneListRef = useRef(doneList)
	
	useEffect(() => {
		leaveListRef.current = leaveList
	}, [leaveList])
	
	useEffect(() => {
		todoListRef.current = todoList
	}, [todoList])
	
	useEffect(() => {
		doneListRef.current = doneList
	}, [doneList])
	
	const statusLabelMap = useMemo(() => ({
		[LeaveStatus.REJECTED]: '未通过',
		[LeaveStatus.PENDING]: '待会签',
		[LeaveStatus.APPROVING]: '待审批',
		[LeaveStatus.COMPLETED]: '已通过',
		[LeaveStatus.CANCELLED]: '已取消',
	}), [])

	const statusColorMap = useMemo(() => ({
		[LeaveStatus.REJECTED]: '#f56565',
		[LeaveStatus.PENDING]: '#ed8936',
		[LeaveStatus.APPROVING]: '#3182ce',
		[LeaveStatus.COMPLETED]: '#38a169',
		[LeaveStatus.CANCELLED]: '#718096',
	}), [])

	// 获取状态标签文本
	const getStatusLabel = useCallback((status: LeaveStatus): string => {
		return statusLabelMap[status] || '未知状态'
	}, [statusLabelMap])

	// 获取状态标签颜色
	const getStatusColor = useCallback((status: LeaveStatus): string => {
		return statusColorMap[status] || '#718096'
	}, [statusColorMap])

	const fetchData = useCallback(async (tab: 'my' | 'todo' | 'done', isRefresh: boolean = false, targetPageNo?: number) => {
		const isMyTab = tab === 'my'
		const isTodoTab = tab === 'todo'
		const isDoneTab = tab === 'done'
		const currentPageNo = targetPageNo || (isRefresh ? 1 : (
			isMyTab ? pageNoRef.current : 
			isTodoTab ? todoPageNoRef.current : 
			donePageNoRef.current
		))
		
		// 设置加载状态
		if (isMyTab) {
			setLoading(true)
			if (isRefresh) {
				setPageNo(1)
				pageNoRef.current = 1
			} else if (targetPageNo) {
				setPageNo(targetPageNo)
				pageNoRef.current = targetPageNo
			}
		} else if (isTodoTab) {
			setTodoLoading(true)
			if (isRefresh) {
				setTodoPageNo(1)
				todoPageNoRef.current = 1
			} else if (targetPageNo) {
				setTodoPageNo(targetPageNo)
				todoPageNoRef.current = targetPageNo
			}
		} else if (isDoneTab) {
			setDoneLoading(true)
			if (isRefresh) {
				setDonePageNo(1)
				donePageNoRef.current = 1
			} else if (targetPageNo) {
				setDonePageNo(targetPageNo)
				donePageNoRef.current = targetPageNo
			}
		}

		try {
			let response: any
			
			if (isMyTab) {
				// 获取我的请假列表
				const params: PageParams = {
					pageNo: currentPageNo,
					pageSize,
				}
				response = await RegisterApi.getRegisterPage(params)
			} else if (isTodoTab) {
				// 获取待批请假列表
				const params = {
					pageNo: currentPageNo,
					pageSize,
					category: '请假登记',
					processDefinitionKey: 'oa_leaveRegister',
				}
				response = await RegisterApi.getRegisterTodoPage(params)
			} else if (isDoneTab) {
				// 获取已批请假列表
				const params = {
					pageNo: currentPageNo,
					pageSize,
					category: '请假登记',
					processDefinitionKey: 'oa_leaveRegister',
				}
				response = await RegisterApi.getRegisterDonePage(params)
			}

			// 解析响应数据
			const responseAny = response as any
			let responseList: any[] = []
			let responseTotal = 0

			if (responseAny && responseAny.list) {
				responseList = responseAny.list
				responseTotal = responseAny.total || 0
			} else if (responseAny && responseAny.data && responseAny.data.list) {
				responseList = responseAny.data.list
				responseTotal = responseAny.data.total || 0
			}

			if (isMyTab) {
				if (isRefresh) {
					setLeaveList(responseList) 
				} else if (responseList.length > 0) {
					setLeaveList(prev => {
						const prevList = prev || []
						const existingIds = new Set(prevList.map(item => item.id).filter(id => id !== undefined))
						const filteredNewList = responseList.filter(item =>
							item.id === undefined || !existingIds.has(item.id)
						)
						return [...prevList, ...filteredNewList]
					})
				}
				setTotal(responseTotal)
			}

			if (isTodoTab || isDoneTab) {
				const basicData = responseList.map((item: any, index: number) => ({
					...item,
					originalIndex: index,
					reasons: item.reasons || '未知'
				}))
				
				if (isTodoTab) {
					if (isRefresh) {
						setTodoList(basicData) 
					} else if (responseList.length > 0) {
						setTodoList(prev => {
							const prevList = prev || []
							const existingIds = new Set(prevList.map(item => item.id).filter(id => id !== undefined))
							const filteredNewList = basicData.filter(item =>
								item.id === undefined || !existingIds.has(item.id)
							)
							return [...prevList, ...filteredNewList]
						})
					}
					setTodoTotal(responseTotal)
				}
				
				if (isDoneTab) {
					if (isRefresh) {
						setDoneList(basicData) 
					} else if (responseList.length > 0) {
						setDoneList(prev => {
							const prevList = prev || []
							const existingIds = new Set(prevList.map(item => item.id).filter(id => id !== undefined))
							const filteredNewList = basicData.filter(item =>
								item.id === undefined || !existingIds.has(item.id)
							)
							return [...prevList, ...filteredNewList]
						})
					}
					setDoneTotal(responseTotal)
				}
				
				if (responseList.length > 0 && isTodoTab) {
					setTodoEnriching(true)
					try {
						const enrichPromises = responseList.map(async (taskItem, index) => {
						try {
							if (taskItem.processInstance?.id) {
								const timeoutDuration = 1500 // 减少到1.5秒超时
								
								const leaveIdPromise = RegisterApi.getRegisterId(taskItem.processInstance.id)
								const leaveIdResponse = await Promise.race([
									leaveIdPromise,
									new Promise((_, reject) => 
										setTimeout(() => reject(new Error('Timeout')), timeoutDuration)
									)
								]) as any
								const leaveId = leaveIdResponse.data
								
								if (leaveId && typeof leaveId === 'number') {
									const leaveDetailPromise = RegisterApi.getRegister(Number(leaveId))
									const leaveDetail = await Promise.race([
										leaveDetailPromise,
										new Promise((_, reject) => 
											setTimeout(() => reject(new Error('Timeout')), timeoutDuration)
										)
									]) as any
									const leaveData = leaveDetail.data || leaveDetail
									return {
										...taskItem,
										leaveDetail: leaveData,
										reasons: taskItem.reasons || leaveData?.reasons || '事假',
										originalIndex: index
									}
								}
							}
							return { ...taskItem, originalIndex: index, reasons: taskItem.reasons || '事假' }
						} catch (error) {
							console.warn('获取请假详情失败:', error)
							return { ...taskItem, originalIndex: index, reasons: taskItem.reasons || '事假' }
						}
					})
					
					const results = await Promise.allSettled(enrichPromises)
					
					const enrichedData = results
						.map(result => result.status === 'fulfilled' ? result.value : null)
						.filter(item => item !== null)
						.sort((a, b) => a.originalIndex - b.originalIndex)
						.map(({ originalIndex: _originalIndex, ...cleanItem }) => cleanItem)
					
					if (isRefresh) {
						setTodoList(enrichedData)
					} else {
						setTodoList(prev => {
							const prevList = prev || []
							const existingIds = new Set(prevList.map(item => item.id).filter(id => id !== undefined))
							const filteredNewList = enrichedData.filter(item =>
								item.id === undefined || !existingIds.has(item.id)
							)
							return [...prevList, ...filteredNewList]
						})
					}
					setTodoTotal(responseTotal)
				} catch (error) {
					console.error('获取请假详情过程中发生错误:', error)
				} finally {
					setTodoEnriching(false)
				}
				}

				// 为已批请假获取详细信息
				if (responseList.length > 0 && isDoneTab) {
					setDoneEnriching(true)
					try {
						const enrichPromises = responseList.map(async (taskItem, index) => {
							try {
								if (taskItem.processInstance?.id) {
									const timeoutDuration = 1500 // 减少到1.5秒超时
									
									const leaveIdPromise = RegisterApi.getRegisterId(taskItem.processInstance.id)
									const leaveIdResponse = await Promise.race([
										leaveIdPromise,
										new Promise((_, reject) => 
											setTimeout(() => reject(new Error('Timeout')), timeoutDuration)
										)
									]) as any
									const leaveId = leaveIdResponse.data
									
									if (leaveId && typeof leaveId === 'number') {
										const leaveDetailPromise = RegisterApi.getRegister(Number(leaveId))
										const leaveDetail = await Promise.race([
											leaveDetailPromise,
											new Promise((_, reject) => 
												setTimeout(() => reject(new Error('Timeout')), timeoutDuration)
											)
										]) as any
										const leaveData = leaveDetail.data || leaveDetail
										return {
											...taskItem,
											leaveDetail: leaveData,
											reasons: taskItem.reasons || leaveData?.reasons || '事假',
											originalIndex: index
										}
									}
								}
								return { ...taskItem, originalIndex: index, reasons: taskItem.reasons || '事假' }
							} catch (error) {
								console.warn('获取请假详情失败:', error)
								return { ...taskItem, originalIndex: index, reasons: taskItem.reasons || '事假' }
							}
						})
						
						const results = await Promise.allSettled(enrichPromises)
						
						const enrichedData = results
							.map(result => result.status === 'fulfilled' ? result.value : null)
							.filter(item => item !== null)
							.sort((a, b) => a.originalIndex - b.originalIndex)
							.map(({ originalIndex: _originalIndex, ...cleanItem }) => cleanItem)
						
						if (isRefresh) {
							setDoneList(enrichedData)
						} else {
							setDoneList(prev => {
								const prevList = prev || []
								const existingIds = new Set(prevList.map(item => item.id).filter(id => id !== undefined))
								const filteredNewList = enrichedData.filter(item =>
									item.id === undefined || !existingIds.has(item.id)
								)
								return [...prevList, ...filteredNewList]
							})
						}
						setDoneTotal(responseTotal)
					} catch (error) {
						console.error('获取已批请假详情过程中发生错误:', error)
					} finally {
						setDoneEnriching(false)
					}
				}
			}
		} catch (error: any) {
			if (error.isAuthError) {
				return;
			}
			
			if (!isRefresh && targetPageNo) {
				if (isMyTab) {
					const previousPageNo = targetPageNo - 1
					setPageNo(previousPageNo)
					pageNoRef.current = previousPageNo
				} else if (isTodoTab) {
					const previousPageNo = targetPageNo - 1
					setTodoPageNo(previousPageNo)
					todoPageNoRef.current = previousPageNo
				} else if (isDoneTab) {
					const previousPageNo = targetPageNo - 1
					setDonePageNo(previousPageNo)
					donePageNoRef.current = previousPageNo
				}
			}
			
			if (isRefresh) {
				if (isMyTab) {
					setLeaveList([])
					setTotal(0)
				} else if (isTodoTab) {
					setTodoList([])
					setTodoTotal(0)
				} else if (isDoneTab) {
					setDoneList([])
					setDoneTotal(0)
				}
			}

			const tabName = isMyTab ? '请假' : isTodoTab ? '待批请假' : '已批请假'
			Alert.alert('错误', `获取${tabName}列表失败，请稍后重试`)
		} finally {
			if (isMyTab) {
				setLoading(false)
			} else if (isTodoTab) {
				setTodoLoading(false)
			} else if (isDoneTab) {
				setDoneLoading(false)
			}
		}
	}, [pageSize])

	// 下拉刷新
	const onRefresh = useCallback(async () => {
		if (activeTab === 'my') {
			setRefreshing(true)
			await fetchData('my', true, 1)
			setRefreshing(false)
			// 刷新完成后滚动到顶部
			setTimeout(() => {
				flatListRef.current?.scrollToOffset({ offset: 0, animated: true })
			}, 100)
		} else if (activeTab === 'todo') {
			setTodoRefreshing(true)
			await fetchData('todo', true, 1)
			setTodoRefreshing(false)
			// 刷新完成后滚动到顶部
			setTimeout(() => {
				flatListRef.current?.scrollToOffset({ offset: 0, animated: true })
			}, 100)
		} else if (activeTab === 'done') {
			setDoneRefreshing(true)
			await fetchData('done', true, 1)
			setDoneRefreshing(false)
			// 刷新完成后滚动到顶部
			setTimeout(() => {
				flatListRef.current?.scrollToOffset({ offset: 0, animated: true })
			}, 100)
		}
	}, [activeTab, fetchData])

	// 加载更多
	const loadMoreTimerRef = useRef<NodeJS.Timeout | null>(null)
	
	const loadMore = useCallback(() => {
		if (loadMoreTimerRef.current) {
			clearTimeout(loadMoreTimerRef.current)
		}
		
		loadMoreTimerRef.current = setTimeout(() => {
			if (activeTab === 'my') {
				if (!loading && leaveList && leaveList.length < total) {
					fetchData('my', false, pageNoRef.current + 1)
				}
			} else if (activeTab === 'todo') {
				if (!todoLoading && todoList && todoList.length < todoTotal) {
					fetchData('todo', false, todoPageNoRef.current + 1)
				}
			} else if (activeTab === 'done') {
				if (!doneLoading && doneList && doneList.length < doneTotal) {
					fetchData('done', false, donePageNoRef.current + 1)
				}
			}
		}, 200) // 200ms 防抖延迟
	}, [activeTab, loading, leaveList, total, todoLoading, todoList, todoTotal, doneLoading, doneList, doneTotal, fetchData])

	// 处理查看详情
	const handleViewDetail = useCallback((item: RegisterVO) => {
		try {
			// 导航到详情页面，传递请假记录ID
			navigation.navigate('LeaveDetail', {
				leaveId: item.id,
				processInstanceId: item.processInstanceId
			})
		} catch (error) {
			Alert.alert('错误', '页面跳转失败，请稍后重试')
		}
	}, [navigation])

	// 处理编辑
	const handleEdit = useCallback((item: RegisterVO) => {
		try {
			// 导航到新增页面，传递编辑数据
			navigation.navigate('LeaveAdd', {
				isEdit: true,
				editData: item
			})
		} catch (error) {
			Alert.alert('错误', '页面跳转失败，请稍后重试')
		}
	}, [navigation])

	// 处理撤销申请
	const handleCancelLeave = useCallback(async (item: RegisterVO) => {
		try {
			// 检查是否有流程实例ID
			if (!item.processInstanceId) {
				Alert.alert('提示', '该申请没有流程实例，无法撤销')
				return
			}
			
			// 检查流程状态
			if (item.status === LeaveStatus.COMPLETED || 
				item.status === LeaveStatus.REJECTED || 
				item.status === LeaveStatus.CANCELLED) {
				Alert.alert('提示', '该申请流程已结束，无法撤销')
				return
			}
			
			// 二次确认
			Alert.alert(
				'撤销申请',
				'确认要撤销该请假申请吗？撤销后，该审批流程将自动结束。',
				[
					{ text: '取消', style: 'cancel' },
					{ 
						text: '确认撤销', 
						style: 'destructive',
						onPress: async () => {
							try {
								await ProcessInstanceApi.cancelProcessInstanceByStartUser(
									item.processInstanceId!,
									'用户主动撤销申请'
								)
								
								Alert.alert('成功', '申请已撤销', [
									{ text: '确定', onPress: () => {
										// 刷新列表
										fetchData('my', true, 1)
									}}
								])
							} catch (error) {
								console.error('撤销申请失败:', error)
								Alert.alert('错误', '撤销申请失败，请稍后重试')
							}
						}
					}
				]
			)
		} catch (error) {
			console.error('撤销申请失败:', error)
			Alert.alert('错误', '撤销申请失败，请稍后重试')
		}
	}, [fetchData])
	
	// 处理新增请假
	const handleAddLeave = useCallback(() => {
		try {
			// 导航到新增页面
			navigation.navigate('LeaveAdd')
		} catch (error) {
			Alert.alert('提示', '页面跳转失败，请稍后重试')
		}
	}, [navigation])

	// 处理查看待批请假详情
	const handleViewTodoDetail = useCallback((item: any) => {
		try {
			if (item.leaveDetail?.id) {
				navigation.navigate('LeaveDetail', {
					leaveId: item.leaveDetail.id,
					processInstanceId: item.processInstance?.id,
					isFromTodo: true, // 标识来自待批请假
					taskId: item.id, // 传递任务ID用于审批操作
					onRefresh: () => fetchData('todo', true, 1) // 传递刷新回调
				})
			} else {
				Alert.alert('提示', '暂无详细信息')
			}
		} catch (error) {
			Alert.alert('错误', '页面跳转失败，请稍后重试')
		}
	}, [navigation, fetchData])

	// 处理查看已批请假详情
	const handleViewDoneDetail = useCallback((item: any) => {
		try {
			if (item.leaveDetail?.id) {
				navigation.navigate('LeaveDetail', {
					leaveId: item.leaveDetail.id,
					processInstanceId: item.processInstance?.id,
					isFromDone: true, // 标识来自已批请假
					onRefresh: () => fetchData('done', true, 1) // 传递刷新回调
				})
			} else {
				Alert.alert('提示', '暂无详细信息')
			}
		} catch (error) {
			Alert.alert('错误', '页面跳转失败，请稍后重试')
		}
	}, [navigation, fetchData])

	// 切换Tab
	const handleTabChange = useCallback((tab: 'my' | 'todo' | 'done') => {
		if (tab === activeTab) return
		
		if (tab === 'my') {
			setLoading(true)
		} else if (tab === 'todo') {
			setTodoLoading(true)
		} else if (tab === 'done') {
			setDoneLoading(true)
		}
		
		setActiveTab(tab)
		
		//检查目标Tab是否已有数据
		const needsRefresh = tab === 'my' 
			? (!leaveList || leaveList.length === 0)
			: tab === 'todo'
			? (!todoList || todoList.length === 0)
			: (!doneList || doneList.length === 0)
		
		if (needsRefresh) {
			// 只在没有数据时才重新获取
			fetchData(tab, true, 1)
		} else {
			// 如果已有数据，清除加载状态
			if (tab === 'my') {
				setLoading(false)
			} else if (tab === 'todo') {
				setTodoLoading(false)
			} else if (tab === 'done') {
				setDoneLoading(false)
			}
		}
		
		// 切换标签时滚动到顶部
		setTimeout(() => {
			flatListRef.current?.scrollToOffset({ offset: 0, animated: true })
		}, 100)
	}, [fetchData, activeTab, leaveList, todoList, doneList])

	// 渲染我的请假记录项
	const renderLeaveItem = useCallback(({ item }: { item: RegisterVO }) => (
		<LeaveItem
			item={item}
			onViewDetail={handleViewDetail}
			onEdit={handleEdit}
			onCancel={handleCancelLeave}
			getStatusLabel={getStatusLabel}
			getStatusColor={getStatusColor}
		/>
	), [handleViewDetail, handleEdit, handleCancelLeave, getStatusLabel, getStatusColor])

	// 渲染待批请假记录项
	const renderTodoItem = useCallback(({ item }: { item: any }) => (
		<TodoItem
			item={item}
			onViewDetail={handleViewTodoDetail}
			onRefresh={() => fetchData('todo', true, 1)}
		/>
	), [handleViewTodoDetail, fetchData])

	// 渲染已批请假记录项
	const renderDoneItem = useCallback(({ item }: { item: any }) => (
		<DoneItem
			item={item}
			onViewDetail={handleViewDoneDetail}
			_onRefresh={() => fetchData('done', true, 1)}
		/>
	), [handleViewDoneDetail, fetchData])

	// 渲染空状态
	const renderEmptyComponent = useCallback(() => {
		// 如果正在加载，不显示空状态
		const isLoading = activeTab === 'my' ? loading : 
			activeTab === 'todo' ? (todoLoading || todoEnriching) :
			(doneLoading || doneEnriching)
		if (isLoading) {
			return null
		}
		
		const emptyText = activeTab === 'my' ? '暂无请假记录' : 
			activeTab === 'todo' ? '暂无待批请假' : '暂无已批请假'
		const buttonText = activeTab === 'my' ? '立即申请' : '刷新'
		
		return (
			<View style={styles.emptyContainer}>
				<Icon
					name="inbox"
					type="feather"
					size={48}
					color="#ccc"
				/>
				<Text style={styles.emptyText}>{emptyText}</Text>
				<Button
					title={buttonText}
					type="outline"
					buttonStyle={styles.emptyButton}
					titleStyle={styles.emptyButtonText}
					onPress={activeTab === 'my' ? handleAddLeave : onRefresh}
				/>
			</View>
		)
	}, [activeTab, loading, todoLoading, todoEnriching, doneLoading, doneEnriching, handleAddLeave, onRefresh])

	const keyExtractor = useCallback((item: any, index: number) => {
		const key = item.id ? `leave-${item.id}` : `leave-index-${index}`
		return key
	}, [])

	const currentData = useMemo(() => {
		return activeTab === 'my' ? (leaveList || []) : 
			activeTab === 'todo' ? (todoList || []) :
			(doneList || [])
	}, [activeTab, leaveList, todoList, doneList])

	const currentRefreshing = useMemo(() => {
		return activeTab === 'my' ? refreshing : 
			activeTab === 'todo' ? todoRefreshing :
			doneRefreshing
	}, [activeTab, refreshing, todoRefreshing, doneRefreshing])

	const currentRenderItem = useMemo(() => {
		return activeTab === 'my' ? renderLeaveItem : 
			activeTab === 'todo' ? renderTodoItem :
			renderDoneItem
	}, [activeTab, renderLeaveItem, renderTodoItem, renderDoneItem])

	useEffect(() => {
		// 初始化时加载我的请假列表
		fetchData('my', true, 1)
	}, [fetchData])

	// 清理定时器
	useEffect(() => {
		return () => {
			if (loadMoreTimerRef.current) {
				clearTimeout(loadMoreTimerRef.current)
			}
		}
	}, [])

	return (
		<SafeAreaView style={styles.container}>
			{/* Tab 切换 */}
			<View style={styles.tabContainer}>
				<TouchableOpacity
					style={[styles.tabItem, activeTab === 'my' && styles.activeTabItem]}
					onPress={() => handleTabChange('my')}
				>
					<Text style={[styles.tabText, activeTab === 'my' && styles.activeTabText]}>
						我的请假
					</Text>
				</TouchableOpacity>
				<TouchableOpacity
					style={[styles.tabItem, activeTab === 'todo' && styles.activeTabItem]}
					onPress={() => handleTabChange('todo')}
				>
					<View style={styles.tabRow}>
						<Text style={[styles.tabText, activeTab === 'todo' && styles.activeTabText]}>
							待批请假
						</Text>
						{activeTab === 'todo' && todoEnriching && (
							<View style={styles.loadingIconContainer}>
								<Icon
									name="sync"
									type="material"
									size={12}
									color="#3182ce"
								/>
							</View>
						)}
					</View>
				</TouchableOpacity>
				<TouchableOpacity
					style={[styles.tabItem, activeTab === 'done' && styles.activeTabItem]}
					onPress={() => handleTabChange('done')}
				>
					<View style={styles.tabRow}>
						<Text style={[styles.tabText, activeTab === 'done' && styles.activeTabText]}>
							已批请假
						</Text>
						{activeTab === 'done' && doneEnriching && (
							<View style={styles.loadingIconContainer}>
								<Icon
									name="sync"
									type="material"
									size={12}
									color="#3182ce"
								/>
							</View>
						)}
					</View>
				</TouchableOpacity>
			</View>

			<FlatList
				ref={flatListRef}
				data={currentData}
				renderItem={currentRenderItem}
				keyExtractor={keyExtractor}
				style={styles.list}
				contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) }}
				refreshControl={
					<RefreshControl
						refreshing={currentRefreshing}
						onRefresh={onRefresh}
						colors={['#3182ce']}
					/>
				}
				ListEmptyComponent={renderEmptyComponent}
				showsVerticalScrollIndicator={false}
				onEndReached={loadMore}
				onEndReachedThreshold={0.2}
				removeClippedSubviews={true}
				maxToRenderPerBatch={5}
				updateCellsBatchingPeriod={30}
				initialNumToRender={8}
				windowSize={10}
				getItemLayout={undefined} 
			/>
		</SafeAreaView>
	)
}

const styles = {
	container: {
		flex: 1,
		backgroundColor: '#f5f5f5',
	},

	tabContainer: {
		flexDirection: 'row' as const,
		backgroundColor: '#fff',
		borderBottomWidth: 1,
		borderBottomColor: '#e5e5e5',
	},
	tabItem: {
		flex: 1,
		paddingVertical: 12,
		alignItems: 'center' as const,
		borderBottomWidth: 2,
		borderBottomColor: 'transparent',
	},
	activeTabItem: {
		borderBottomColor: '#3182ce',
	},
	tabText: {
		fontSize: 16,
		color: '#666',
		fontWeight: '500' as const,
	},
	activeTabText: {
		color: '#3182ce',
		fontWeight: '600' as const,
	},
	list: {
		flex: 1,
	},
	cardContainer: {
		borderRadius: 12,
		marginHorizontal: 16,
		marginVertical: 8,
		backgroundColor: '#fff',
		shadowColor: 'transparent',
		shadowOffset: {
			width: 0,
			height: 0,
		},
		shadowOpacity: 0,
		shadowRadius: 0,
		elevation: 0,
		borderWidth: 0,
	},
	cardHeader: {
		flexDirection: 'row' as const,
		justifyContent: 'space-between' as const,
		alignItems: 'flex-start' as const,
		marginBottom: 12,
	},
	leftSection: {
		flexDirection: 'row' as const,
		alignItems: 'center' as const,
		flex: 1,
	},
	avatar: {
		backgroundColor: '#409EFF',
		marginRight: 12,
	},
	avatarText: {
		color: '#fff',
		fontSize: 16,
		fontWeight: '600' as const,
	},
	headerInfo: {
		flex: 1,
	},
	titleText: {
		fontSize: 16,
		fontWeight: '600' as const,
		color: '#333',
		marginBottom: 4,
	},
	subtitleText: {
		fontSize: 14,
		color: '#666',
	},
	timeText: {
		fontSize: 12,
		color: '#999',
		marginLeft: 8,
	},
	cardContent: {
		marginBottom: 16,
	},
	contentText: {
		fontSize: 14,
		color: '#666',
		lineHeight: 20,
		marginBottom: 4,
	},
	contentRow: {
		flexDirection: 'row' as const,
		alignItems: 'flex-start' as const,
		marginBottom: 8,
	},
	contentLabel: {
		fontSize: 14,
		color: '#666',
		width: 80,
		fontWeight: '500' as const,
	},
	contentValue: {
		fontSize: 14,
		color: '#333',
		flex: 1,
		lineHeight: 20,
	},
	cardFooter: {
		flexDirection: 'column' as const,
		alignItems: 'flex-start' as const,
	},
	buttonRow: {
		flexDirection: 'row' as const,
		justifyContent: 'space-between' as const,
		alignItems: 'center' as const,
		width: '100%' as const,
	},
	statusSection: {
		marginBottom: 1,
	},
	statusBadge: {
		borderRadius: 12,
		paddingHorizontal: 8,
		paddingVertical: 8,
		minHeight: 32,
	},
	statusBadgeText: {
		fontSize: 12,
		fontWeight: '500' as const,
	},
	actionSection: {
		flexDirection: 'row' as const,
		gap: 8,
	},
	fullWidthRejectButton: {
		flex: 1,
		backgroundColor: '#fff',
		borderColor: '#FF4D4F',
		borderWidth: 1,
		borderRadius: 8,
		paddingVertical: 6,
	},
	fullWidthApproveButton: {
		flex: 1,
		backgroundColor: '#52C41A',
		borderRadius: 8,
		paddingVertical: 6,
	},
	rejectButtonText: {
		color: '#FF4D4F',
		fontSize: 14,
		fontWeight: '500' as const,
	},
	approveButtonText: {
		color: '#fff',
		fontSize: 14,
		fontWeight: '500' as const,
	},
	fullWidthButton: {
		flex: 1,
	},
	actionButton: {
		borderColor: '#409EFF',
		borderRadius: 15,
		paddingHorizontal: 12,
		paddingVertical: 4,
		minWidth: 60,
	},
	actionButtonText: {
		color: '#409EFF',
		fontSize: 12,
		fontWeight: '500' as const,
	},
	cancelActionButton: {
		paddingHorizontal: 12,
		paddingVertical: 4,
		minWidth: 60,
		borderColor: '#ff4040ff',
		borderRadius: 15,
	},
	cancelActionText: {
		color: '#ff4040ff',
		fontSize: 12,
		fontWeight: '500' as const,
	},
	tabRow: {
		flexDirection: 'row' as const,
		alignItems: 'center' as const,
	},
	loadingIconContainer: {
		marginLeft: 5,
	},
	emptyContainer: {
		flex: 1,
		justifyContent: 'center' as const,
		alignItems: 'center' as const,
		paddingVertical: 80,
	},
	emptyText: {
		fontSize: 16,
		color: '#999',
		marginVertical: 16,
	},
	emptyButton: {
		borderColor: '#409EFF',
		borderRadius: 20,
		paddingHorizontal: 24,
	},
	emptyButtonText: {
		color: '#409EFF',
		fontSize: 14,
	},
	approvedText: {
		color: '#38a169',
		fontWeight: '500' as const,
	},
	approvedBadge: {
		backgroundColor: '#38a169',
	},
}

export default Leave